package com.tian.exception;

import com.tian.enums.ResultCode;
import com.tian.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * {@code @description:} 统一返回参数
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-07-28 15:21
 * {@code @version:} 1.0
 */
@RestControllerAdvice
@Slf4j
public class GlobalAdvice {

    @ExceptionHandler(Exception.class)
    public Result doException(Exception e) {

        log.error("统一异常处理机制，触发异常 msg ", e);
        String message = null;
        int errorCode = ResultCode.FAIL.getCode();
        //自定义异常
        if (e instanceof BusinessException) {
            BusinessException exception = (BusinessException) e;
            message = exception.getMessage();
            errorCode = exception.getCode();
        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            message = "不支持GET/POST方法";
        } else if (e instanceof NoHandlerFoundException) {
            message = "请求接口不存在";
        } else if (e instanceof MissingServletRequestParameterException) {
            errorCode = ResultCode.PARAMETER_IS_NULL.getCode();
            message = String.format("缺少必要参数[%s]", ((MissingServletRequestParameterException) e).getParameterName());
        } else if (e instanceof MethodArgumentNotValidException) {
            BindingResult result = ((MethodArgumentNotValidException) e).getBindingResult();
            FieldError error = result.getFieldError();
            errorCode = ResultCode.PARAMETER_IS_NULL.getCode();
            message = error == null ? ResultCode.PARAMETER_ERROR.getMessage() : error.getDefaultMessage();
        } else if (e instanceof BindException) {
            errorCode = ResultCode.PARAMETER_IS_NULL.getCode();
            message = ((BindException) e).getFieldError().getDefaultMessage();
        } else if (e instanceof IllegalArgumentException) {
            errorCode = ResultCode.PARAMETER_IS_NULL.getCode();
            message = e.getMessage();
        } else if (e instanceof RuntimeException) {
            errorCode = ResultCode.FAIL.getCode();
            message = e.getMessage();
        }
        return Result.fail(errorCode, message);
    }
}
